package com.yjc.blog.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yjc.blog.domain.bo.EBookDao;
import com.yjc.blog.domain.bo.EbookSave;
import com.yjc.blog.domain.po.Ebook;
import com.yjc.blog.domain.vo.EBookVO;
import com.yjc.blog.domain.vo.PageVO;
import com.yjc.blog.mapper.EbookMapper;
import com.yjc.blog.service.IEbookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjc.blog.utils.CopyUtil;
import com.yjc.blog.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 电子书 服务实现类
 * </p>
 *
 * @author yjc
 * @since 2024-10-27
 */
@Service
public class EbookServiceImpl extends ServiceImpl<EbookMapper, Ebook> implements IEbookService {

    @Autowired
    private SnowFlake snowFlake;
    /**
     * 返回所有电子书合集
     *
     * @return
     */
    @Override
    public PageVO<EBookVO> listAll() {
        List<Ebook> list = this.list();
        List<EBookVO> vos = new ArrayList<>();
        for (Ebook ebook : list) {
            EBookVO vo = new EBookVO();
            BeanUtil.copyProperties(ebook,vo);
            vos.add(vo);
        }
        PageVO<EBookVO> pageVO = new PageVO<>();
        pageVO.setList(vos);
        return pageVO;

    }

    /**
     * 根据dao进行模糊匹配
     * @param bookDao
     * @return
     */
    @Override
    public PageVO<EBookVO> getByDao(EBookDao bookDao) {
        List<EBookVO> vos = new ArrayList<>();
        if (ObjectUtil.isNull(bookDao)){
            //TODO 统一进行依次处理
        }

        Long id = bookDao.getId();
        String name = bookDao.getName();
        PageHelper.startPage(bookDao.getPage(),bookDao.getSize());
        List<Ebook> list = this.lambdaQuery()
                .eq(id != null, Ebook::getId, id)
                .or()
                .eq(name != null, Ebook::getName, name)
                .list();
        for (Ebook ebook : list) {
            EBookVO vo = new EBookVO();
            BeanUtil.copyProperties(ebook,vo);
            vos.add(vo);
        }
        PageInfo<EBookVO> info = new PageInfo(vos);
        PageVO<EBookVO> pageVO = new PageVO<>();
        pageVO.setList(vos);
        pageVO.setTotal(info.getTotal());
        return pageVO;
    }

    @Override
    public void save(EbookSave save) {
        Ebook ebook = CopyUtil.copy(save, Ebook.class);
        if (ObjectUtil.isEmpty(ebook.getId())){
            long nextId = snowFlake.nextId();
            ebook.setId(nextId);
            this.save(ebook);
        }
        else {
            this.lambdaUpdate()
                    .eq(Ebook::getId,ebook.getId())
                    .update(ebook);
        }
    }

    @Override
    public void delete(Long id) {
       this.removeById(id);
    }
}
